<template>
  <el-popover v-model="visible" width="400" trigger="manual">
    <el-button size="mini" type="primary" plain slot="reference" @click="visible=true">更改手机号</el-button>
    <div v-if="first">
      <h3 class="tc">完成以下认证</h3>
      <el-divider></el-divider>
      <p>请输入{{hiddenMobile}}收到的短信验证码</p>
      <el-input class="mt-20" placeholder="请输入验证码" v-model="valideCode">
        <template slot="append">
          <span v-show="show" @click="sendMsg(mobile)" class="pointer">验证码</span>
          <span v-show="!show" class="count pointer">{{count}} s</span>
        </template>
      </el-input>
    </div>
    <div v-else>
      <h3 class="tc">输入新手机号</h3>
      <el-divider></el-divider>
      <el-form
        ref="updateMobileForm"
        :model="updateMobileForm"
        :rules="rules"
        label-width="70px"
        size="small"
      >
        <el-form-item label="新手机号" prop="newMobile">
          <el-input placeholder="请输入新手机号" v-model="updateMobileForm.newMobile"></el-input>
        </el-form-item>
        <el-form-item label="验证码" prop="newValideCode">
          <el-input placeholder="请输入验证码" v-model="updateMobileForm.newValideCode">
            <template slot="append">
              <span v-show="show1" @click="send1" class="pointer">验证码</span>
              <span v-show="!show1" class="count pointer">{{count1}} s</span>
            </template>
          </el-input>
        </el-form-item>
      </el-form>
    </div>
    <el-divider></el-divider>
    <div class="tc">
      <el-button size="small" class="mr-10" plain @click="visible=false">取消</el-button>
      <el-button
        size="small"
        type="primary"
        :disabled="!valideCode"
        @click="validPass"
        v-if="first"
      >下一步</el-button>
      <el-button size="small" type="primary" @click="updateNewMobile" v-else>完成</el-button>
    </div>
  </el-popover>
</template>

<script>
import {
  getMobileValideCode,
  checkMobileValideCode,
  modifyUserMobile
} from "api/user";
import { validPhone } from "@/utils/validate";
const TIME_COUNT = 60; //更改倒计时时间
export default {
  props: ["mobile", "userId"],
  data() {
    const validateMobile = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("请输入手机号"));
      }
      setTimeout(() => {
        if (!validPhone(value)) {
          callback(new Error("手机号不正确"));
        } else {
          callback();
        }
      }, 300);
    };
    return {
      submiting: false,
      visible: false, //当前手机验证
      first: true, //修改新手机
      valideCode: "",
      show: true, // 初始启用按钮
      count: "", // 初始化次数
      timer: null,
      show1: true, // 初始启用按钮
      count1: "", // 初始化次数
      timer1: null,
      updateMobileForm: {
        newMobile: "",
        newValideCode: ""
      },
      rules: {
        newMobile: [{ validator: validateMobile, trigger: "blur" }],
        newValideCode: [
          { required: true, message: "验证码不能为空", trigger: "blur" }
        ]
      }
    };
  },
  computed: {
    hiddenMobile() {
      return this.mobile.substr(0, 3) + "****" + this.mobile.substr(7);
    }
  },
  methods: {
    // 获取验证码
    sendMsg(mobile) {
      if (!mobile) return;
      getMobileValideCode({ mobile })
        .then(() => {
          if (this.first) {
            this.countDown("timer", "count", "show");
          } else {
            this.countDown("timer1", "count1", "show1");
          }
          this.$confirm("验证码已发送至登记手机号上，请查收。", {
            confirmButtonText: "确定",
            center: true
          });
        })
        .catch(err => {
          this.$message.error(err.message);
        });
    },
    send1() {
      this.$refs.updateMobileForm.validateField("newMobile", phoneError => {
        if (!phoneError) {
          this.sendMsg(this.updateMobileForm.newMobile);
        }
      });
    },
    // 倒计时
    countDown(timer, count, show) {
      if (!this[timer]) {
        this[count] = TIME_COUNT;
        this[show] = false;
        this[timer] = setInterval(() => {
          if (this[count] > 0 && this[count] <= TIME_COUNT) {
            this[count]--;
          } else {
            this[show] = true;
            clearInterval(this[timer]); // 清除定时器
            this[timer] = null;
          }
        }, 1000);
      }
    },
    //校验验证码
    validPass() {
      let data = {
        mobile: this.mobile,
        valideCode: this.valideCode
      };
      checkMobileValideCode(data)
        .then(res => {
          if (res.code === "0000") {
            this.first = false;
          }
        })
        .catch(err => {
          this.$message.error(err.msg);
        });
    },
    // 修改新手机号
    updateNewMobile() {
      this.$refs.updateMobileForm.validate(valid => {
        if (valid) {
          if (this.submiting) return;
          this.submiting = true;
          let data = {
            userId: this.userId,
            oldMobile: this.mobile,
            oldMobileCode: this.valideCode,
            newMobile: this.updateMobileForm.newMobile,
            newMobileCode: this.updateMobileForm.newValideCode
          };
          modifyUserMobile(data)
            .then(res => {
              this.visible = false;
              this.$message.success("新手机号修改成功！");
              this.$emit("getNewMobile", this.updateMobileForm.newMobile);
            })
            .catch(err => {
              this.$message.error(err.msg);
            });
        } else {
        }
      });
    }
  }
};
</script>

<style lang='scss' scoped>
</style>
